package com.example.hobbyplanetserve.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hobbyplanetserve.entity.MyTUserDetail;
import com.example.hobbyplanetserve.entity.User;
import com.example.hobbyplanetserve.mapper.UserMapper;
import com.example.hobbyplanetserve.properties.JwtProperties;
import com.example.hobbyplanetserve.utils.JwtUtils;
import com.example.hobbyplanetserve.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    JwtProperties jwtProperties;

    @Resource
    private UserMapper userMapper;

    @Autowired
    SecurityUtils securityUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        System.out.println("前端的token信息=======>"+token);
        //如果token为空直接放行，由于用户信息没有存放在SecurityContextHolder.getContext()中所以后面的过滤器依旧认证失败符合要求
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }

//        解析Jwt中的用户id
        Claims claims = JwtUtils.getClaimsByToken(token,jwtProperties.getAdminSecretKey());
        long userId= Long.parseLong(claims.getId());

        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", userId);
        User user = userMapper.selectOne(queryWrapper);

        // 将 User 封装为 MyTUserDetail
        MyTUserDetail userDetail = new MyTUserDetail();
        userDetail.setUser(user);


        //将用户信息存放在SecurityContextHolder.getContext()，后面的过滤器就可以获得用户信息了。这表明当前这个用户是登录过的，后续的拦截器就不用再拦截了
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(userDetail,null,null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //获取用户信息
        MyTUserDetail currentUserDetail = securityUtils.getCurrentUserDetail();
        log.info("当前用户信息：{}", currentUserDetail);

        filterChain.doFilter(request,response);
    }
}